package _01版本;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


//[ [1,1] [1,2] [1,3] ]
		//[ [1,2] [1,3] [1,4] ]
				//[ [1,3] [1,4] [1,5] ]
				//[ [1,3] [1,4] [1,5] [1,6]]

public class GridLayoutFrame extends JFrame implements KeyListener{
	
	final int N = 20;
	
	// 蛇头
		int x=5;
		int y=5;
		
		int foodX;
		int foodY;
		
		List<Coordinate> l1 = new ArrayList<Coordinate>();
		
		
		// 存放界面上所有的格子
		ArrayList<JPanel> cells = new ArrayList<>(); 
		
		public GridLayoutFrame() {
		
			
			JPanel p1 = new JPanel();
			this.add(p1);
			// 10行10列 间隔
			p1.setLayout(new GridLayout(N,N,1,1));
			
			for(int i=1;i<=N*N;i++)
			{
				JPanel p = new JPanel();
				p.setBackground(Color.white);
				p1.add(p);
				
				cells.add(p);
			}
			// 
			p1.setFocusable(true);
			foodaddress();
			snakeaddress();
			// 添加键盘监听
			p1.addKeyListener(this);
			
			
		}

		@Override
		public void keyPressed(KeyEvent e) {
		
		}

		@Override
		public void keyReleased(KeyEvent e) {
			int oldX = x;
			int oldY = y;
			
			switch(e.getKeyCode())
			{
			case 38:
				y--;
				break;
			case 40:
				y++;
				break;
			case 37:
				x--;
				break;
			case 39:
				x++;
				break;
			}
			
			
			int oldIndex = oldY*N+oldX;
			cells.get(oldIndex).setBackground(Color.white);	
			
			// 把蛇所在的位置颜色要修改
			int index = y*N+x;
			cells.get(index).setBackground(Color.red);
			if(foodX == x && foodY == y)
			{
				foodaddress();
			}
		}
		
		public void snakeaddress()
		{
			x = (int) (Math.random() * N);
			y = (int) (Math.random() * N);
			int index = y*N+x;
			cells.get(index).setBackground(Color.red);	
		}
		
		public void foodaddress()
		{
			foodX = (int) (Math.random() * N);
			foodY = (int) (Math.random() * N);
			int index = foodY*N+foodX;
			cells.get(index).setBackground(Color.pink);	
		}
		

		@Override
		public void keyTyped(KeyEvent e) {
			// TODO Auto-generated method stub
			
		}
}